from __future__ import division
import es
import cPickle
from os.path import isfile

class DB(object):
    def __init__(self):
        self.database = es.getAddonPath('aa') + '/absolutadmin_ranks.db'
    def loadDatabase(self):
        if isfile(self.database):
            f = open(self.database, 'rb')
            l = cPickle.load(f)
            f.close()
            return l
        return {}
    def saveDatabase(self):
        f = open(self.database, 'wb')
        cPickle.dump(player, f, cPickle.HIGHEST_PROTOCOL)
        f.close()
    def sortRank(self, steam):
        ranks = []
        for _steam in player:
            ranks.append(player[_steam].getKDR(True))
        ranks.sort(cmp=None, key=None, reverse=True)      
        return ranks.index(player[steam].getKDR()) + 1
db = DB()

class Player:
    def __init__(self, steam):
        self.kills = self.deaths = self.kdr = self.name = 0
    def setName(self, name):
        self.name = name
    def addKill(self):
        self.kills += 1
    def addDeath(self):
        self.deaths += 1
    def getKills(self):
        return self.kills
    def getDeaths(self):
        return self.deaths
    def getKDR(self, sort=False):
        if sort:
            self.kdr = self.kills if not self.deaths else self.kills / self.deaths
        return self.kdr
    def getName(self):
        return self.name

def getPlayer(steam):
    return Player(steam)

def uniqueID(userid):
    steam = es.getplayersteamid(userid)
    if steam == 'BOT':
        steam = 'BOT_%s' % es.getplayername(userid)
    return steam
